package org.kfive.nova.thread;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * Created by Administrator on 2017/4/14.
 */
public class CountTask extends RecursiveTask<Integer> {
    private static final Integer THRESHOLD=2;
    private Integer[] data;

    public CountTask(Integer[] data){
        this.data = data;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        if(data.length<=THRESHOLD){
            List<Integer> list = Arrays.asList(data);
            for(Integer n : list){
                sum = sum+n;
            }
        }else {
            int length = data.length;
            int mind = length/2;
            Integer [] upData = Arrays.copyOfRange(data,0,mind);
            Integer [] downDate = Arrays.copyOfRange(data,mind,length);
            CountTask upTask = new CountTask(upData);
            CountTask downTask = new CountTask(downDate);
            upTask.fork();
            downTask.fork();
            int upResult = upTask.join();
            int downResult = downTask.join();
            sum = upResult+downResult;
        }
        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        Integer[] data = new Integer[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
        CountTask task = new CountTask(data);
        Future<Integer> sum = pool.submit(task);
        try {
            System.out.println(sum.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
